package com.ljw.servlet_springMVC.annotation.conf;

import com.ljw.servlet_springMVC.annotation.intercept.MyIntercept;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.CacheControl;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.time.Duration;

/**
 * @FileName ServletConfig
 * @Description TODO Servlet的web容器的配置类。
 * 实现WebMvcConfigurer接口，可定制springMVC的其他功能：视图解析器，拦截器等
 * @Author ljw
 * @Date 2021/2/5 14:25
 * @Version 1.0
 */
//Servlet的web容器 处理 controller层、viewResolver、拦截器、过滤器等，只扫描@Controller注解
//禁用默认过滤规则 ：useDefaultFilters = false
@Configuration
@ComponentScan(basePackages = {"com.ljw.servlet_springMVC.annotation"},includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
},useDefaultFilters = false)
@EnableWebMvc
public class ServletConfig implements WebMvcConfigurer{

    //视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        //开启内容协商：使用MappingJackson2JsonView
        //registry.enableContentNegotiation(new MappingJackson2JsonView());
        //默认从"/WEB-INF/"下获取 ".jsp"页面
        //registry.jsp();
        //自定义前后缀
        registry.jsp("/views/jsp/",".jsp");
    }

    //将springmvc处理不了的静态资源交给tomcat处理，这样就可以访问静态资源了。相当于<mvc:default-servlet-handler/>
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        //开启tomcat中的servlet容器处理 静态资源的功能
        configurer.enable();
    }

    //设置静态资源 映射路径 和 资源位置 和 缓存时间
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //  http://localhost:8080/resources/1.jpg
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public", "classpath:/static/")
                .setCacheControl(CacheControl.maxAge(Duration.ofDays(365)));

       /* 相当于：
        <mvc:resources mapping="/resources/**"
        location="/public, classpath:/static/"
        cache-period="31556926" />*/
    }


    //拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截所有的controller方法的映射路径（"/**"），但排除"/admin/**"
        registry.addInterceptor(new MyIntercept()).addPathPatterns("/**").excludePathPatterns("/admin/**");
    }


}
